package org.chen.service.impl;

import org.chen.common.request.LoginRequest;
import org.chen.common.response.LoginResponse;
import org.chen.common.token.FrontTokenComponent;
import org.chen.common.user.User;
import org.chen.common.utils.RedisUtil;
import org.chen.service.LoginService;
import org.chen.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FrontTokenComponent tokenComponent;

    /**
     * 账号密码登录
     *
     * @return LoginResponse
     */
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        User user = new User();
        user.setUid(1);
        user.setAccount(UUID.randomUUID().toString());
//        if (ObjectUtil.isNull(user)) {
//            throw new CrmebException("此账号未注册");
//        }
//        if (!user.getStatus()) {
//            throw new CrmebException("此账号被禁用");
//        }
//
//        // 校验密码
//        String password = CrmebUtil.encryptPassword(loginRequest.getPassword(), loginRequest.getPhone());
//        if (!user.getPwd().equals(password)) {
//            throw new CrmebException("密码错误");
//        }
//
        LoginResponse loginResponse = new LoginResponse();
//        String token = tokenComponent.createToken(user);
//        loginResponse.setToken(token);
//
//        //绑定推广关系
//        if (loginRequest.getSpreadPid() > 0) {
//            bindSpread(user, loginRequest.getSpreadPid());
//        }
//
//        // 记录最后一次登录时间
//        user.setLastLoginTime(DateUtil.nowDateTime());
//        userService.updateById(user);
//
//        loginResponse.setUid(user.getUid());
//        loginResponse.setNikeName(user.getNickname());
//        loginResponse.setPhone(user.getPhone());
        String token = tokenComponent.createToken(user);
        loginResponse.setToken(token);
        return loginResponse;
    }

    /**
     * 推出登录
     * @param request HttpServletRequest
     */
    @Override
    public void loginOut(HttpServletRequest request) {
        tokenComponent.logout(request);
    }
}
